<template>
  <div v-loading="isLoading" class="w300">
    <el-autocomplete
      v-if="!isInElectronBrowser"
      v-model="folderPath"
      placeholder="创建新项目的文件夹"
      :fetch-suggestions="querySearchAsync"
      class="w300"
    >
      <template #append>
        <el-button @click="handleCreateNewProj">复制当前项目</el-button>
      </template>
    </el-autocomplete>
    <div v-else>
      <el-button @click="electronSelectFolder">复制当前项目</el-button>
    </div>
  </div>
</template>
<script setup lang="ts">
import axios from "axios";
import { ElMessageBox, ElNotification } from "element-plus";
import { h, ref } from "vue";

let isInElectronBrowser = (() => {
  try {
    require("@electron/remote").getCurrentWindow();
    return true;
  } catch (error) {
    return false;
  }
})();

let isLoading = ref(false);

const folderPath = ref((await axios.post("/api/project-folder")).data);

async function electronSelectFolder() {
  let { dialog } = require("@electron/remote");
  let { filePaths } = await dialog.showOpenDialog({
    properties: ["openDirectory"],
  });
  if (filePaths && filePaths.length) {
    folderPath.value = filePaths[0];
    handleCreateNewProj();
  }
}

async function handleCreateNewProj() {
  let isProjCreated = false;
  let toPost = {
    path: folderPath.value,
  };
  try {
    await ElMessageBox({
      type: "info",
      title: "创建新项目",
      showCancelButton: true,
      message: h("div", {}, [
        h("div", {}, `项目将复制到:`),
        h("div", {}, folderPath.value),
        h("div", {}, `该目录下的所有文件将会被清空，是否继续？`),
      ]),
    });
    isProjCreated = true;
    isLoading.value = true;
    let { data } = await axios.post("/api/create-project", toPost);
    await ElMessageBox({
      type: "info",
      showCancelButton: true,
      message: "yarn install ?",
    });
    await axios.post("/api/create-project-yarn", toPost);
    return ElNotification(data);
  } catch (error) {
    ElNotification({
      message: "操作已取消",
    });
  } finally {
    isProjCreated &&
      axios.post("/api/open-project-folder", {
        path: folderPath.value,
      });
    isLoading.value = false;
  }
}
async function querySearchAsync(queryString: string) {
  let { data } = await axios.post("/api/search-folder", { queryString });
  data.push(queryString);
  data = data.map(
    (
      e: {
        value: string;
      }[]
    ) => ({ label: e, value: e })
  );
  // cb(data);
  return data;
}
</script>
<style scoped lang="scss">
.flex {
  display: flex;
}
.w300 {
  text-align: center;
}
</style>
